# -*- coding: utf-8 -*-
import os, sys
from django.conf import settings
from elasticsearch import Elasticsearch
from blog.models import BlogMsg


class BLogElasticSearchClient(object):

    def __init__(self):
        self.index_name = 'blog'
        self.index_type = 'doc'
        self.es = Elasticsearch([settings.ELASTIC_SEARCH_ADDR],
                                port=settings.ELASTIC_SEARCH_PORT)

    def create_index(self):
        _index_mapping = {
            "mappings": {
                self.index_type: {
                    "properties": {
                        "title": {
                            "type": "text",
                            "analyzer": "ik_max_word",
                            "search_analyzer": "ik_max_word"
                        },
                        "content": {
                            "type": "text",
                            "analyzer": "ik_max_word",
                            "search_analyzer": "ik_max_word"
                        }
                    }
                }
            }
        }
        if self.es.indices.exists(index=self.index_name) is not True:
            self.es.indices.create(index=self.index_name, body=_index_mapping)

    def bulk_index_data(self):
        blogs = BlogMsg.objects.filter(is_public=0)
        bulk_data = []
        for blog in blogs:
            action_type = {
                'index': {
                    '_index': self.index_name,
                    '_type': self.index_type,
                    '_id': blog.id
                }
            }
            action = {
                "title": blog.title,
                "content": blog.blog_content
            }
            bulk_data.append(action_type)
            bulk_data.append(action)
        return self.es.bulk(bulk_data, index=self.index_name, doc_type=self.index_type)

    def rebuild_index(self):
        if self.es.indices.exists(index=self.index_name):
            self.es.indices.delete(index=self.index_name)
        self.create_index()

    def search(self, key_words, orign=0, to=5):
        response = self.es.search(
            index=self.index_name,
            body={
                "query": {
                    "multi_match": {
                        "query": key_words,
                        "fields": ["title", "content"]
                    }
                },
                "from": orign,
                "size": to,
                "highlight": {
                    "pre_tags": ['<span class="keyword">'],
                    "post_tags": ['</span>'],
                    "fields": {
                        "title": {},
                        "content": {},
                    }
                }
            }
        )
        total_nums = response["hits"]["total"]
        data = {}
        for hit in response["hits"]["hits"]:
            hit_dict = {}
            if "title" in hit["highlight"]:
                hit_dict["title"] = hit["highlight"]["title"]
            if "content" in hit["highlight"]:
                hit_dict["content"] = hit["highlight"]["content"]
            data[int(hit["_id"])] = hit_dict
        return data


if __name__ == '__main__':
    es = BLogElasticSearchClient()
    # es.create_index()
    # es.bulk_index_data()
    print es.search(u"电信")
